package k8s_ui

import (
	"errors"
	"github.com/wonderivan/logger"
	"k8s-platform/db"
	"k8s-platform/model"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

var K8s k8s

type k8s struct {
	ClientSet       *kubernetes.Clientset
	kubeconfigBytes []byte //ssh连接接口
}

// 返回集群列表ID给前端展示，集群池数量
//func (k *k8s) GetK8sList() (k8s_names []string, err error) {
//	var k8s_name []string
//	tx := db.DB.Table("createk8s").Pluck("k8s_name", &k8s_name)
//	if tx.Error != nil && tx.Error.Error() != "record not found" {
//		logger.Error("获取k8s_name列表数据失败" + tx.Error.Error())
//		return k8s_name, errors.New("获取k8s_name列表数据数据失败" + tx.Error.Error())
//	}
//	return k8s_name, nil
//}

func (k *k8s) GetK8sList() (k8slist []model.Createk8s, err error) {
	var k8sData []model.Createk8s
	tx := db.DB.Find(&k8sData)
	if tx.Error != nil && tx.Error.Error() != "未找到集群信息" {
		logger.Error("未找到集群信息" + tx.Error.Error())
		return nil, errors.New("未找到集群信息" + tx.Error.Error())
	}
	// Return all fetched data
	return k8sData, nil
}

// 多集群切换池 DelK8s
func (k *k8s) IntPool(pool string) (k8sid *model.Createk8s, err error) {
	//pool = "a1集群"
	k8sid = &model.Createk8s{}
	tx := db.DB.Where("k8s_name = ?", pool).First(&k8sid)
	if tx.Error != nil && tx.Error.Error() != "record not found" {
		logger.Error("获取K8s_config_token数据k8s_name失败" + tx.Error.Error())
		return nil, errors.New("获取K8s_config_token数据k8s_name失败，请检查数据库连接是否正常" + tx.Error.Error())
	}

	var Kubeconfig = k8sid.K8s_config_token
	kubeconfigBytes := []byte(Kubeconfig)

	//clientcmd.BuildConfigFromFlags源码格式要求 （usr地址，config文件路径）必选其中一个
	//conf, err := clientcmd.BuildConfigFromFlags("", config.Kubeconfig)
	//clientcmd.RESTConfigFromKubeConfig 接受从数据库中获取的token信息源码要求为byte类型，所以需要转换
	conf, err := clientcmd.RESTConfigFromKubeConfig(kubeconfigBytes)
	if err != nil {
		logger.Error("切换K8s_config_token对象错误或指定路径不正确,"+pool, err)
	}
	//将配置好的文件对象传入kubernetes.NewForConfig接收接口
	clientSet, err := kubernetes.NewForConfig(conf)
	if err != nil {
		logger.Error("切换k8s clientSet实例化失败,", err, pool)
	} else {
		logger.Info("切换k8s clientSet实例化成功,集群名称:", pool)
	}
	//实例化clientSet
	k.kubeconfigBytes = kubeconfigBytes //ssh连接接口实例化
	k.ClientSet = clientSet             //k8s api接口访问实例化

	db.DB.Model(&model.Createk8s{}).Where("k8s_name = ?", pool).Updates(map[string]interface{}{"Status": "SUCCESS"})

	//改造支持多人同时选择多实例访问不冲突
	//当前端以a1集群名称访问时候，注册A1

	return k8sid, err
}
